package com.atguigu.flink.chapter11;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.Csv;
import org.apache.flink.table.descriptors.FileSystem;
import org.apache.flink.table.descriptors.Schema;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/10/22 8:52
 */
public class Flink04_Table_File {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        StreamTableEnvironment tenv = StreamTableEnvironment.create(env);
        // 文件如何切割
        // 表的元数据信息
        Schema schema = new Schema()
            .field("id", DataTypes.STRING())
            .field("ts", DataTypes.BIGINT())
            .field("vc", DataTypes.INT());
        tenv
            .connect(new FileSystem().path("input/sensor.txt"))
            .withFormat(new Csv().lineDelimiter("\n").fieldDelimiter(','))
            .withSchema(schema)
            .createTemporaryTable("sensor");
        
        Table resultTable = tenv
            .from("sensor")
            .where($("id").isEqual("sensor_1"))
            .select($("id"), $("vc"));
        
        // 建立动态表与文件(sink)进行关联
        tenv
            .connect(new FileSystem().path("input/a.txt"))
            .withFormat(new Csv().lineDelimiter(""))
            .withSchema(new Schema()
                            .field("id", DataTypes.STRING())
                            .field("vc", DataTypes.INT()))
            .createTemporaryTable("a");
        
        // 把数据写入到与sink关联的临时表中(动态表)
        resultTable.executeInsert("a");
        
    }
}
